/*
 * @Description:
 * @Version: 2.0
 * @Autor: zhangjx
 * @Date: 2023-05-25 14:11:19
 * @LastEditors: uphldjx 1373577124@qq.com
 * @LastEditTime: 2024-07-27 17:05:40
 */
import router from '@/router'
import { useRouterStore } from '@/stores/router'

import { defineStore } from 'pinia'
import apiMod from '@/apiMod/index'
import { encryption } from '@/utils/encdecrpt'
import { removeStore, setStore, getStore } from '@/utils/store'
import { treeTransArray, hasRouteChildren, treeFindList } from '@/utils/util'
// import {xxtea_decrypt} from '@/utils/xxtea.js'
import { uniqueId } from 'lodash-es'

export const useUserStore = defineStore('user', () => {
	const userInfo = ref(getStore('userInfo') || {})
	const permissions = ref(getStore('permissions') || {})
	const menuData: any = ref([])
	const topMenu: any = ref([])
	const breadcrumbList: any = ref([])
	const activeTopMenu = ref(getStore('activeTopMenu') || {})

	const userLogin = (form: any, type: string) => {
		return new Promise((resolve, reject) => {
			const user = encryption({
				data: form,
				param: ['password'],
			})
			apiMod
				.loginByUsername(user)
				.then(async (res) => {
					userInfo.value = res?.user_info || {}
					let auth = {}
					userInfo.value.authorities.map((item) => {
						auth[item.authority] = true
					})
					permissions.value = auth
					setStore('permissions', auth)
					setStore('access_token', res.access_token)
					setStore('refresh_token', res.refresh_token)
					// res.user_info.username = xxtea_decrypt(res.user_info.username)
					// 在此处获取详细的用户信息
					apiMod.sys_user_value().then((theUser) => {
						// 保存他的角色信息
						setStore('detailUserInfo', theUser.data)
					})
					setStore('userInfo', res.user_info)
					resolve('ok')
				})
				.catch((err) => {
					reject(err)
				})
		})
	}

	const userSSOLogin = (code, token_str) => {
		return new Promise((resolve, reject) => {
			apiMod
				.ssoLogin(code, token_str)
				.then((res) => {
					userInfo.value = res?.user_info || {}
					let auth = {}
					userInfo.value.authorities.map((item) => {
						auth[item.authority] = true
					})
					permissions.value = auth
					setStore('permissions', auth)
					setStore('access_token', res.access_token)
					setStore('refresh_token', res.refresh_token)
					// res.user_info.username = xxtea_decrypt(res.user_info.username)
					setStore('userInfo', res.user_info)
					resolve('ok')
				})
				.catch((err) => {
					reject(err)
				})
		})
	}

	const getMenus = (menuSource) => {
		function maker(menus, sourceItem) {
			const path = sourceItem.path || uniqueId('apld-menu-empty-')
			let menu: any = {}
			menu = { ...sourceItem }
			menu.title = sourceItem.label ? sourceItem.label : sourceItem.name
			menu.meta = {
				icon: sourceItem.icon,
				title: sourceItem.label ? sourceItem.label : sourceItem.name,
				src: path,
			}
			if (hasRouteChildren(sourceItem)) {
				menu.showComm = true
				menu.children = sourceItem.children.reduce(maker, [])
			}
			menu.menuIndex = sourceItem.path + '__' + sourceItem.id
			menu.unpath = sourceItem.path + '__' + uniqueId('apld-menu')
			if (sourceItem.type == 2 && sourceItem.parentId === -1 && sourceItem.children.length === 0) {
				topMenu.value.push(menu)
			} else {
				menus.push(menu)
			}
			return menus
		}
		return menuSource.reduce(maker, [])
	}

	const GetUserInfo = () => {
		return new Promise((resolve, reject) => {
			apiMod.admin_menu({ deviceType: 0, type: 0, parentId: activeTopMenu.value.id || -1 }).then((res) => {
				const data = res.data.filter((item) => item.type == 0)
				const flatData = treeTransArray(data)
				const menu = getMenus(data)
				menuData.value = menu
				resolve(flatData)
			})
		})
	}
	// 设置顶部菜单
	const setTopMenuInfo = (menu) => {
		activeTopMenu.value = menu
		setStore('activeTopMenu', menu)
		GetUserInfo()
		// 激活路由
		const useRouter = useRouterStore()
		useRouter.LoadRecRoute(router)
	}

	// 设置面包屑
	const LoadBreadcrumb = (path) => {
		breadcrumbList.value = treeFindList(menuData.value, path.meta.menuId)
	}
	const resfreshUserAuth = () => {
		removeStore('activeTopMenu')
		apiMod.sys_user_value().then((res) => {
			if (res.data?.permissions) {
				let auth = {}
				res.data.permissions.map((item) => {
					auth[item] = true
				})
				setStore('permissions', auth)
			}
		})
	}
	const userLoginOut = () => {
		removeStore('access_token')
		removeStore('refresh_token')
		removeStore('top-menu')
		removeStore('permissions')
		removeStore('organizationInfo')
		removeStore('activeTopMenu')
		removeStore('userInfo')

		if (!window.location.hash.includes('demo') && window.location.hash !== '#/sso') {
			window.location.reload()
		}
	}
	return {
		permissions,
		userInfo,
		menuData,
		breadcrumbList,
		activeTopMenu,
		setTopMenuInfo,
		userLogin,
		userSSOLogin,
		userLoginOut,
		GetUserInfo,
		LoadBreadcrumb,
		resfreshUserAuth,
	}
})
